package base

import (
	"encoding/xml"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"

	//使用mssql数据库
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

//WebContext Web上下文
type WorkFlowContext struct {
	XMLName   xml.Name   `xml:"WorkFlows"`
	WorkFlows []WorkFlow `xml:"WorkFlow"`
}

func (w *WorkFlowContext) GetWorkFlow(name string) *WorkFlow {
	for _, wf := range w.WorkFlows {
		if wf.Name == name {
			return &wf
		}
	}
	return nil
}

//WorkFlow WorkFlow参数
type WorkFlow struct {
	Name    string   `xml:"name,attr"`
	Actions []Action `xml:"Action"`
}

//Action Action
type Action struct {
	Step      int    `xml:"step,attr"`
	Desc      string `xml:"desc,attr"`
	Execute   string `xml:"execute,attr"`
	Isinorgan bool   `xml:"isinorgan,attr"`
}

var WFContext WorkFlowContext

func initWF() {
	var err error
	var workPath string
	if workPath, err = WorkDir(); err != nil {
		Logger.Error(fmt.Sprintf("获取执行路径出错%s", err))
		return
	}
	filePath := workPath + "/config/workflow.xml"
	if xmlBytes, err := ioutil.ReadFile(filePath); err == nil {
		if err := xml.Unmarshal(xmlBytes, &WFContext); err != nil {
			Logger.Error(fmt.Sprintf("加载WorkFlow配置文件失败%s", err))
		}
	}
}

// WorkDir 获取绝对工作路径
func WorkDir() (string, error) {
	execPath, err := ExecPath()
	if err != nil {
		return execPath, err
	}
	return execPath, nil
}

//ExecPath 获取程序运行路径
func ExecPath() (string, error) {
	file, err := os.Getwd()
	if err != nil {
		return "", err
	}
	p, err := filepath.Abs(file)
	if err != nil {
		return "", err
	}
	return p, nil
}
